<script setup>
import { useRouter, useRoute } from 'vue-router';
import { useUserStore } from '@/stores/index.js'
import { ref, onMounted } from 'vue';
import {  ElMessage} from 'element-plus';
import request from '@/utils/request.js';

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
let questionId1 = route.query.questionId;

// 补全初始嵌套字段，避免渲染时访问undefined
const questionDetail = ref({
  id: '',
  asker: { avatar: '', username: '' },
  answers: [],
  title: '',
  content: '',
  tags: [],
  answerCount: 0,
  collectCount: 0,
  viewCount: 0,
  createdAt: ''
});
// 热门问题
const hotQuestionList = ref([]);
//绑定回答输入框内容
const answerContent = ref('');
// 新增：加载状态（避免重复提交）
const submitLoading = ref(false);
//点赞状态
const likeStatus1 = ref({});
// dislikeStatus1存储每个回答的踩状态，
const dislikeStatus1 = ref({});
//收藏状态
const collectStatus1 = ref(false);
// 回答操作列表（点赞、踩等）
let answerOpList = ref([]);


const getQuestionDetail = async () => {
  try {
    const res = await request.get('/getQuestionDetail', {
      params: { id: questionId1 }
    });
    questionDetail.value = { ...questionDetail.value, ...res.data };
  } catch (err) {
    console.error('问题详情加载失败：', err);
  }
};
const getHotQuestions = async () => {
  try {
    const res = await request.get('/getHotQuestions');
    hotQuestionList.value = res.data.hotQuestions;
  } catch (err) {
    console.error('热门问题加载失败：', err);
  }
};

// 新增：提交回答核心逻辑
const submitAnswer = async () => {
  // 1. 输入验证（补充长度校验，与后端呼应）
  if (!answerContent.value.trim()) {
    ElMessage.error('回答不能为空！');
    return;
  }
  if (answerContent.value.trim().length < 5 || answerContent.value.trim().length > 2000) {
    ElMessage.error('回答内容需在5-2000字之间！');
    return;
  }

  // 3. 防止重复提交
  submitLoading.value = true;
  try {
    // 4. 调用接口（参数与后端一致，无需调整）
    const res = await request.post('/submitAnswer', {
      questionId: questionId1,
      content: answerContent.value.trim(),
      authorId: userStore.userId // 必传，后端已校验
    });

    // 关键修复：读取后端返回的正确层级（res.data.data.xxx）
    const { answer: newAnswer, updatedQuestion } = res.data;

    // 5. 补全字段（仅补全必要字段，删除冗余的collectCount）
    const completeAnswer = {
      id: newAnswer.id, // 用后端返回的真实ID，无需临时ID
      questionId: newAnswer.questionId,
      author: {
        id: userStore.userId,
        username: newAnswer.author.username || '我',
        avatar: newAnswer.author.avatar || 'https://picsum.photos/id/64/36/36'
      },
      content: newAnswer.content,
      likeCount: newAnswer.likeCount || 0,
      dislikeCount: newAnswer.dislikeCount || 0,
      createdAt: newAnswer.createdAt // 用后端返回的时间，保持数据一致
    };

    // 6. 实时更新页面（用后端返回的统计数据，避免前端计算偏差）
    questionDetail.value.answers.unshift(completeAnswer); // 插入列表顶部
    questionDetail.value.answerCount = updatedQuestion.answerCount; // 同步后端返回的回答数
    questionDetail.value.hotScore = updatedQuestion.hotScore; // 同步更新后的热度值

    // 7. 清空输入框
    answerContent.value = '';
    ElMessage.success('回答提交成功！');

  } catch (err) {
    console.error('回答提交失败：', err);
    // 优化错误提示：优先显示后端返回的具体原因
    ElMessage.error(err.response?.data?.message || '回答提交失败，请稍后再试！');
  } finally {
    submitLoading.value = false;
  }
};
//点赞
const likeAnswer = async (answerId) => {
  try {
    // 调用后端切换接口，获取最新状态和数据
    const res = await request.post('/likeAnswer', {
      answerId, // 简化参数写法（键值同名）
      userId: userStore.userId // 必传：用户ID（后端需要判断是谁的操作）
    });

    const { newLikeCount, isLiked ,answerNewHotScore} = res.data; // 后端返回的关键数据
    const {message} = res;

    // 1. 更新对应回答的点赞数（用后端返回值，避免前端计算错误）
    const index = questionDetail.value.answers.findIndex(a => a.id === answerId);
    if (index !== -1) {
      questionDetail.value.answers[index].likeCount = newLikeCount;
    }

    // 2. 更新点赞状态（直接用后端返回的isLiked，确保前后端一致）
    likeStatus1.value[answerId] = isLiked;

    //更新热度;
    const index1 = questionDetail.value.answers.findIndex(a => a.id === answerId);
    if (index1 !== -1) {
      questionDetail.value.answers[index1].hotScore = answerNewHotScore;
    }
    // 3. 显示后端返回的提示（点赞/取消点赞区分）
    ElMessage.success(message);

  } catch (err) {
    console.error('操作失败：', err);
    ElMessage.error(err.response?.data?.message || '操作失败，请稍后再试！');
  }
};
//踩
const dislikeAnswer = async (answerId) => {
  try {
    const res = await request.post('/dislikeAnswer', {
      answerId,
      userId: userStore.userId
    });

    const { newDislikeCount, isDisliked } = res.data;
    const {message} = res;
    // 更新对应回答的踩数
    const index = questionDetail.value.answers.findIndex(a => a.id === answerId);
    if (index !== -1) {
      questionDetail.value.answers[index].dislikeCount = newDislikeCount;
    }

    // 更新踩状态
    dislikeStatus1.value[answerId] = isDisliked;

    ElMessage.success(message);
  } catch (err) {
    console.error('操作失败：', err);
    ElMessage.error(err.response?.data?.message || '操作失败，请稍后再试！');
  }
};
//获得用户对回答的操作状态（点赞、踩）
const getUserAnswerOpStatus = async (questionId) => {
  try {

    const res = await request.post('/getUserAnswerOpStatus', {
      questionId:questionId1, // 正确传参：问题ID（后端接收的参数名）
      userId: userStore.userId // 当前用户ID（必传，后端需判断用户）
    });

    answerOpList = res.data; // 后端返回的所有回答状态数组

    // 遍历状态数组，更新本地Map（关键：用answerId关联）
    answerOpList.forEach(item => {
      const { answerId, likeStatus, dislikeStatus } = item;
      likeStatus1.value[answerId] = likeStatus; // 对应回答的点赞状态
      dislikeStatus1.value[answerId] = dislikeStatus; // 对应回答的踩状态
    });
    console.log("所有回答操作状态：", likeStatus1.value, dislikeStatus1.value);

  } catch (err) {
    console.error('获取用户操作状态失败：', err);
  }
};
// 收藏/取消收藏
const collectQuestion = async () => {
  try {
    // 1. 新增参数校验：确保必要参数存在
    if (!questionId1 || !userStore.userId) {
      ElMessage.warning('参数异常，请刷新页面重试');
      return;
    }

    // 2. 调用接口，获取最新状态和数据
    const res = await request.post('/collectQuestion', {
      questionId: questionId1,
      userId: userStore.userId
    });

    // 3. 读取正确层级的响应数据
    const { newCollectCount, isCollected } = res.data;
    const {message} = res;
    console.log(newCollectCount);
    // 4. 显示正确提示语
    ElMessage.success(message);

    // 5. 更新本地收藏数
    if (questionDetail.value.id === Number(questionId1)) {
      console.log("相等");
      questionDetail.value.collectCount = newCollectCount;
    }

    // 6. 同步收藏状态（关键：更新响应式变量，实现按钮切换）
    collectStatus1.value = isCollected;

  } catch (err) {
    console.error('收藏问题失败：', err);
    // 错误提示：优先用后端返回的message，无则用默认
    ElMessage.error(err.response?.data?.message || '收藏失败，请稍后再试！');
  }
};
// 获取用户对当前问题的收藏状态
const getUserQuestionCollectStatus = async (questionId) => {
  try {
    const res = await request.post('/getUserQuestionCollectStatus', {
      userId: userStore.userId,
      questionId: questionId1
    });

    // 更新本地收藏状态（直接用后端返回的布尔值）
    collectStatus1.value = res.data.collectStatus;

  } catch (err) {
    console.error('查询收藏状态失败：', err);
    ElMessage.error(err.response?.data?.message || '查询失败，请稍后再试！');
  }
}
const getHotQuestionsDetail = async (hotQuestionId) => {
  try {
     questionId1=hotQuestionId;
     getQuestionDetail();
     getUserAnswerOpStatus();
     getUserQuestionCollectStatus();
  } catch (err) {
    console.error('获取热门问题失败：', err);
    ElMessage.error(err.response?.data?.message || '加载数据失败，请稍后再试！');
  }
}
//按最热回答数排序（按热度从小到大）
const sortAnswersByHot = () => {
  // 升序排序（兼容null，将null视为0）
questionDetail.value.answers.sort((a, b) => {
  const scoreA = a.hotScore || 0;
  const scoreB = b.hotScore || 0;
  return scoreB - scoreA;
});}
//按最新回答时间排序
const sortAnswersByNew = () => {
  // 降序排序（最新在前）
questionDetail.value.answers.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
};
onMounted(() => {
  getQuestionDetail();
  getHotQuestions();
  getUserAnswerOpStatus();
  getUserQuestionCollectStatus();
});
</script>
<template>
  <div class="layout" style="min-height: 100vh;">
    <!-- 头部区域 -->
    <header class="page-header">
      <div class="header-container">
        <button class="back-btn" @click="router.push({
          path: '/headYes/partner/question',
          query: { id: 4 }
        })">← 返回问题列表</button>
        <h1 class="page-title">问答详情</h1>
        <div class="header-empty"></div> <!-- 占位保持标题居中 -->
      </div>
    </header>

    <div class="main-container">
      <div class="main-content">
        <!-- 问题详情卡片：仅当title存在时渲染 -->
        <div class="question-detail-card" v-if="questionDetail.title">
          <div class="question-header">
            <h2 class="question-title">{{ questionDetail.title }}</h2>
            <div class="question-tags">
              <span
                v-for="tag in questionDetail.tags"
                :key="tag"
                class="detail-tag"
              >
                {{ tag }}
              </span>
            </div>
          </div>

          <div class="question-content">
            {{ questionDetail.content || '无问题描述' }}
          </div>

          <div class="question-meta">
            <div class="asker-info">
              <!-- 头像兜底：接口无头像时显示默认图 -->
              <img
                :src="questionDetail.asker.avatar || 'https://picsum.photos/id/64/48/48'"
                class="avatar"
                alt="用户头像"
              />
              <div class="asker-text">
                <div class="nickname">{{ questionDetail.asker.username || '匿名用户' }}</div>
                <!-- 时间兜底：无时间时显示默认文本 -->
                <div class="create-time">
                  {{ questionDetail.createdAt ? questionDetail.createdAt.replace('T', ' ').slice(0, 16) : '未知时间' }}
                </div>
              </div>
            </div>

            <div class="question-stats">
              <div class="stat-item" @click="collectQuestion(questionDetail.id)">
                <span class="stat-icon" style="color: #f56c6c">⭐</span>
                <span class="stat-value">{{ questionDetail.collectCount }}</span>
                <span class="stat-label">
                   {{ collectStatus1 ? '取消收藏' : '收藏问题' }}
                </span>
              </div>
              <div class="stat-item">
                <span class="stat-icon">👁️</span>
                <span class="stat-value">{{ questionDetail.viewCount }}</span>
                <span class="stat-label">浏览</span>
              </div>

            </div>
          </div>
        </div>

        <!-- 回答区域：仅当有回答数量时渲染 -->
        <div class="submit-answer-card">
            <textarea
              placeholder="写下你的回答..."
              rows="5"
              class="answer-textarea"
              v-model="answerContent"
            />
           <button class="submit-btn" @click="submitAnswer" :disabled="submitLoading">
            <span v-if="submitLoading">⏳ 提交中...</span>
            <span v-else>📤 提交回答</span>
          </button>
          </div>
        <div class="answer-section" v-if="questionDetail.answerCount > 0">

           <div class="answer-header">
            <h3>{{ questionDetail.answerCount }} 条回答</h3>
            <button class="answer-btn" @click="sortAnswersByNew()">最新</button>
            <span>|</span>
            <button class="answer-btn" @click="sortAnswersByHot()">最热</button>
          </div>
          <!-- 回答列表：初始为空数组，v-for无报错 -->
          <div
            v-for="(answer, index) in questionDetail.answers"
            :key="answer.id || index"
            class="answer-card"
          >
            <div class="answer-header">
              <img
                :src="answer.author.avatar || 'https://picsum.photos/id/0/36/36'"
                class="answerer-avatar"
                alt="回答者头像"
              />
              <div class="answerer-info">
                <div class="answerer-name">{{ answer.author.username || '匿名用户' }}</div>
                <div class="answer-time">
                  {{ answer.createdAt ? answer.createdAt.replace('T', ' ').slice(0, 16) : '未知时间' }}
                </div>
              </div>
            </div>
            <div class="answer-content">{{ answer.content || '无回答内容' }}</div>
            <div class="answer-actions">
              <button class="like-btn" @click="likeAnswer(answer.id)" >
                 {{ likeStatus1[answer.id] ? '❤️ 取消' : '👍 点赞' }}({{ answer.likeCount || 0 }})
              </button>
              <button class="dislike-btn" @click="dislikeAnswer(answer.id)" >
                {{ dislikeStatus1[answer.id] ? '👎 取消' : '👎 踩' }}({{ answer.dislikeCount || 0 }})
              </button>
            </div>
          </div>
        </div>

        <!-- 无数据提示：无问题标题时显示 -->
        <div v-else style="text-align: center; padding: 48px; color: #1a4e3d;">
          暂无回答，快来抢沙发吧！
        </div>
      </div>

      <!-- 热门问题侧边栏 -->
      <div class="hot-aside">
        <div class="hot-questions">
          <div class="hot-title">
            热门问题
            <span class="hot-arrow">⭐</span>
          </div>
          <ul class="hot-list">
            <li v-for="(item, index) in hotQuestionList" :key="index" class="hot-item"
              @click="getHotQuestionsDetail(item.id)"
            >
              <div class="hot-list-number">{{ index + 1 }}</div>
              <span class="hot-list-content">{{ item.title }}</span>
              <span class="hotness">热度 {{ item.hotScore }}</span>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 基础布局样式 */
.layout {
  padding: 0;
  font-family: 'Microsoft YaHei', sans-serif;
  background-color: #e6f7ef;
  display: flex;
  flex-direction: column;
}

/* 头部样式 */
.page-header {
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  padding: 16px 0;
  margin-bottom: 20px;
}

.header-container {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px;
}

.back-btn {
  background-color: #f0f9f5;
  color: #1a4e3d;
  border: none;
  border-radius: 8px;
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.3s;
}

.back-btn:hover {
  background-color: #d1fae5;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #1a4e3d;
  margin: 0;
}

.header-empty {
  width: 120px; /* 与返回按钮宽度一致，保持标题居中 */
}

/* 主容器样式 */
.main-container {
  position: relative;
  max-width: 1200px;
  width: auto;
  width: 100%;
  margin: 0 auto;
  display: flex;
  gap: 20px;
  flex: 1;
  padding: 0 24px 24px;
}

.main-content {
  padding: 0;
  flex: 1;
}

/* 问题详情卡片样式 */
.question-detail-card {
  background-color: #fff;
  border-radius: 12px;
  margin-bottom: 24px;
  padding: 24px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.question-header .question-title {
  font-size: 20px;
  font-weight: 600;
  color: #1a4e3d;
  margin-bottom: 16px;
}

.question-tags {
  margin-bottom: 20px;
}

.detail-tag {
  background-color: #f0f9f5;
  color: #1a4e3d;
  border: 1px solid #d1fae5;
  margin-right: 8px;
  border-radius: 16px;
  padding: 4px 12px;
  font-size: 14px;
}

.question-content {
  font-size: 16px;
  line-height: 1.8;
  color: #333;
  margin-bottom: 24px;
  white-space: pre-line; /* 保留换行符 */
}

.question-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 16px;
  border-top: 1px solid #f0f9f5;
}

.asker-info {
  display: flex;
  align-items: center;
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
}

.asker-text {
  margin-left: 12px;
}

.nickname {
  font-size: 14px;
  font-weight: 500;
  color: #1a4e3d;
}

.create-time {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.question-stats {
  display: flex;
  gap: 24px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #666;
  cursor: default;
}

.stat-icon {
  font-size: 18px;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 14px;
  font-weight: 600;
}

.stat-label {
  font-size: 12px;
  color: #666;
}

/* 回答区域样式 */
.answer-section {
  margin-bottom: 32px;
}

.answer-header h3 {
  font-size: 18px;
  color: #1a4e3d;
  margin-bottom: 16px;
  font-weight: 600;
}
.answer-btn{
  background-color: #e6f7ef;
  color:rgb(0, 102, 255);
  border: none;
  border-radius: 8px;
  padding: 6px 4px;
  font-size: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
  transition: all 0.3s;
}
.answer-btn:hover{
  background-color: #d1fae5;
}
.answer-btn :first{
  padding-left: 8px;
}

.submit-answer-card {
  background-color: #fff;
  border-radius: 12px;
  margin-bottom: 24px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.answer-textarea {
  width: 100%;
  background-color: #f9fafb;
  outline: none;
  border: none;
  color: #333;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 16px;
  resize: none;
  font-family: inherit;
  font-size: 14px;
}

.submit-btn {
  background-color: #34b518;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 8px 16px;
  font-size: 14px;
  cursor: not-allowed;
  float: right;
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
}

/* 回答卡片样式 */
.answer-card {
  background-color: #fff;
  border-radius: 12px;
  margin-bottom: 16px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.answer-card:hover {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.answer-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.answerer-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
}

.answerer-info {
  margin-left: 10px;
}

.answerer-name {
  font-size: 14px;
  font-weight: 500;
  color: #1a4e3d;
}

.answer-time {
  font-size: 12px;
  color: #666;
  margin-top: 2px;
}

.answer-content {
  font-size: 15px;
  line-height: 1.6;
  color: #333;
  margin-bottom: 16px;
  white-space: pre-line;
}
.answer-actions {
  display: flex;
  align-items: center;
}
.answer-actions .like-btn ,
.answer-actions .dislike-btn {
  color: #666;
  background: transparent;
  border: none;
  cursor: pointer;
  font-size: 14px;
  padding: 4px 0;
  display: flex;
  align-items: center;
  gap: 4px;
  margin-right: 16px;
}

/* 热门侧边栏样式 */
.hot-aside {
  width: 320px;
  margin-top: 0;
  position: sticky;
  top: 24px;
  height: fit-content;
}

.hot-questions {
  padding: 24px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.hot-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 16px;
  color: #1a4e3d;
}

.hot-arrow {
  cursor: default;
  color: red;
}

.hot-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.hot-item {
  font-size: 14px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
  margin: 10px 0;
  line-height: 1.5;
  height: auto;
  display: flex;
  align-items: flex-start;
  cursor: pointer;
}

.hot-item:hover {
  background-color: #f0f0f0;
}

.hot-item:last-child {
  border-bottom: none;
}

.hotness {
  color: #1a4e3d;
  margin-left: 8px;
  font-size: 13px;
  white-space: nowrap;
}

.hot-list-number {
  color: red;
  font-size: 18px;
  font-weight: 600;
  margin-right: 8px;
  line-height: 1.5;
}

.hot-list-content {
  max-width: 230px;
  height: auto;
  flex: 1;
}

/* 响应式适配 */
@media (max-width: 1200px) {
  .header-container {
    padding: 0 16px;
  }

  .main-container {
    max-width: 100%;
    padding: 0 16px 24px;
    flex-direction: column;
  }

  .main-content {
    margin-right: 0;
    width: 100%;
  }

  .hot-aside {
    position: static;
    width: 100%;
    margin-top: 20px;
    max-height: none;
  }

  .question-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
}
</style>
